package com.sync;

/**
 * 对象锁 代码块形式
 *
 * 类锁 ：java类可能有很多个对象，但是只有一个class对象
 * */
public class SyncObjectCodeBlock1 implements Runnable {
    static SyncObjectCodeBlock1 sync = new SyncObjectCodeBlock1();
    static int i = 0;
    Object lock1 = new Object();
    Object lock2 = new Object();
    @Override
    public void run() {
        synchronized (this){
            System.out.println("我是对象锁的代码块形式 我叫"+Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("运行完毕"+Thread.currentThread().getName());
            System.out.println(i);
        }
        synchronized (lock1){
            System.out.println("我是lock1锁的代码块形式 我叫"+Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("运行完毕"+Thread.currentThread().getName());
            System.out.println(i);
        }
        synchronized (lock1){
            System.out.println("我是lock2锁的代码块形式 我叫"+Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("运行完毕"+Thread.currentThread().getName());
            System.out.println(i);
        }
    }


    public static void main(String[] args) {
        Thread t1 = new Thread(sync);
        Thread t2 = new Thread(sync);
        t1.start();
        t2.start();
        //通过isAlive方法检测是否线程还在继续存活
        while(t1.isAlive() || t2.isAlive());

        System.out.println("finished");

    }
}
